<template>

  <div class="container">
    <div class="card1">
      <div class="title">二维码生成</div>
      <div class="lcontainer">
        <div class="qrleft">
          <div class="qrimg">
            <img v-if="qrCodeUrl" ref="myImg" :src="qrCodeUrl" alt="生成的二维码" style="max-height: 100%" />
          </div>
          <div class="save">
            <MButton @click="saveImage">保存</MButton>
          </div>
        </div>
        <div class="qright">
          <div style="width: 70%;">
            <div style="font-size: 14px;">二维码信息</div>
            <div>
              <div style="font-size: 12px;margin-bottom: 5px;margin-top: 15px;">版本</div>
              <input class="minput" style="width: 100%;" disabled v-model="selectedVersioninfo" />
              <div style="font-size: 12px;margin-bottom: 5px;margin-top: 15px;">纠错等级</div>
              <input class="minput" style="width: 100%;" disabled v-model="selectedLevelinfo" />
              <div style="font-size: 12px;margin-bottom: 5px;margin-top: 15px;">编码方式</div>
              <input class="minput" style="width: 100%;" disabled v-model="selectedEncodinginfo" />
            </div>
          </div>

        </div>
      </div>
    </div>
    <div class="card2">
      <div class="title">二维码生成设置</div>
      <div class="container_set">
        <div>
          <MButton :class="button1Class" @click="changeTab('1')">
            基础配置
          </MButton>
          <MButton :class="button2Class" @click="changeTab('2')">
            高级配置
          </MButton>
        </div>
        <div style="margin-top: 20px;" v-if="tabType === '1'">
          <form @submit.prevent="submitForm">
            <div style="font-size: 12px;margin-bottom: 5px;">二维码内容</div>
            <textarea placeholder="请输入二维码内容" rows="4" id="qrInfo" v-model="qrInfo"
              style="width: 100%;background: #F2F3F5;border: none;font-size: 12px;margin-bottom: 15px;padding: 10px;"></textarea>
            <br />
            <div style="font-size: 12px;">纠错等级</div>
            <select v-model="selectedLevel" id="qrLevel"
              style="width: 40%;background: #F2F3F5;border: none;font-size: 12px;height: 28px;margin-bottom: 15px;">
              <option value="L">L(7%)</option>
              <option value="M">M(15%)</option>
              <option value="Q">Q(25%)</option>
              <option value="H">H(30%)</option>
            </select>
            <br />
            <div style="text-align: center;">
              <MButton type="submit">生成</MButton>
            </div>
            <img style="display: none;" ref="myImg2" :src="qrCodeUrl2" alt="生成的二维码" @load="onImageLoad2">
          </form>
        </div>
        <div style="margin-top: 20px;" v-if="tabType === '2'">
          <form @submit.prevent="submitForm2">
            <div style="font-size: 12px;margin-bottom: 5px;">二维码内容</div>
            <textarea placeholder="请输入二维码内容" rows="4" id="qrInfo" v-model="qrInfo"
              style="width: 100%;background: #F2F3F5;border: none;font-size: 12px;margin-bottom: 15px;padding: 10px;"></textarea>
            <br />
            <div style="display:flex;">
              <div style="flex: 1 1 100px;">
                <div style="font-size: 12px;">版本</div>
                <select v-model="selectedVersion" id="qrVersion"
                  style="width: 60%;background: #F2F3F5;border: none;font-size: 12px;height: 28px">
                  <option v-for="num in numbers" :value="num + 1" :key="num">{{ num + 1 }}</option>
                </select>
              </div>
              <div style="flex: 1 1 100px;">
                <div style="font-size: 12px;">纠错等级</div>
                <select v-model="selectedLevel" id="qrLevel"
                  style="width: 60%;background: #F2F3F5;border: none;font-size: 12px;height: 28px">
                  <option value="L">L(7%)</option>
                  <option value="M">M(15%)</option>
                  <option value="Q">Q(25%)</option>
                  <option value="H">H(30%)</option>
                </select>
              </div>
            </div>
            <br />
            <div style="font-size: 12px;">编码方式</div>
            <select v-model="selectedEncoding" id="qrLevel"
              style="width: 30%;background: #F2F3F5;border: none;font-size: 12px;height: 28px;margin-bottom: 15px;">
              <option value="numeric">数字模式</option>
              <!-- <option value="alphanumeric">字母数字模式</option> -->
              <option value="byte">字节模式</option>
            </select>
            <div style="text-align: center;">
              <MButton type="submit">生成</MButton>

            </div>
          </form>
          <img style="display: none;" ref="myImg1" :src="qrCodeUrl1" alt="生成的二维码" @load="onImageLoad1">


        </div>
      </div>
    </div>
  </div>

</template>

<script>
import MButton from '../components/MButton.vue'
import Jsqr from 'jsqr';
import { ref } from 'vue';
import QRCode from 'qrcode';
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  components: {
    MButton,

  },
  setup() {
    const myImg = ref("")
    const myImg1 = ref("")
    const myImg2 = ref("")
    const selectedLevel = ref('L')
    const selectedVersion = ref('1')
    const selectedEncoding = ref('numeric')
    const selectedLevelinfo = ref('L')
    const selectedVersioninfo = ref('1')
    const selectedEncodinginfo = ref('数字模式')
    const qrInfo = ref('');
    const numbers = ref(Array.from({ length: 40 }, (_, i) => i));
    const tabType = ref("1")
    const button1Class = ref('selTab');
    const button2Class = ref('defaultTab');
    const qrCodeUrl = ref("");
    const qrCodeUrl1 = ref("");
    const qrCodeUrl2 = ref("");
    const saveImage = () => {
      if (qrCodeUrl.value !== "") {
        // 提取 Base64 数据部分（去掉前缀）
        const base64Data = qrCodeUrl.value.split(',')[1];

        // 创建一个 Blob 对象
        const blob = base64ToBlob(base64Data, 'image/jpeg'); // 注意 MIME 类型应该与你的图片数据相匹配

        // 创建一个临时的 <a> 元素
        const a = document.createElement('a');

        // 创建一个指向 Blob 对象的 URL
        const url = URL.createObjectURL(blob);

        // 设置 <a> 元素的 href 属性为 Blob URL
        a.href = url;

        // 设置下载的文件名
        a.download = 'image.jpg'; // 你可以根据需要更改文件名

        // 触发点击事件以下载文件
        document.body.appendChild(a);
        a.click();

        // 从 DOM 中移除 <a> 元素
        document.body.removeChild(a);

        // 释放 Blob URL
        URL.revokeObjectURL(url);
      } else {
        alert("请先生成二维码")
      }

    };
    const base64ToBlob = (base64, mimeType) => {
      // 将 Base64 数据转换为 ArrayBuffer
      const byteString = atob(base64);
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }

      // 创建一个 Blob 对象
      return new Blob([ab], { type: mimeType });
    };
    const analysisQr = (img) => {
      if (!img) {
        console.log('未获取到图片元素，请检查。');
        return;
      }
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
      const qrCode = Jsqr(imageData, canvas.width, canvas.height);
      return qrCode
    }
    const onImageLoad2 = () => {
      var img = myImg2.value
      var qrCode = analysisQr(img)
      if (qrCode) {
        selectedEncodinginfo.value = getEncodeing(qrCode.data.length > 0 ? qrCode.chunks[0].type : '');
        selectedVersioninfo.value = qrCode.version;
        selectedLevelinfo.value = selectedLevel.value
        qrCodeUrl.value = qrCodeUrl2.value
        qrCodeUrl2.value = ""
      }
    };
    const onImageLoad1 = async () => {
      var img = myImg1.value
      var qrCode = analysisQr(img)

      if (qrCode) {
        if (qrCode.version > selectedVersion.value) {
          alert("版本过低,建议使用版本" + qrCode.version)
        } else {
          selectedEncodinginfo.value = getEncodeing(qrCode.data.length > 0 ? qrCode.chunks[0].type : '');
          selectedVersioninfo.value = selectedVersion.value;
          selectedLevelinfo.value = selectedLevel.value
          const dataUrl = await QRCode.toDataURL(qrInfo.value, {
            errorCorrectionLevel: selectedLevel.value,
            version: selectedVersion.value,
            encodeURI: selectedEncoding.value,
          });

          qrCodeUrl.value = dataUrl
        }
      }
      qrCodeUrl1.value = ""
    };
    const getEncodeing = (type) => {
      if (type == "numeric") {
        return "数字模式"
      } else if (type == "alphanumeric") {
        return "字母数字模式"
      } else {
        return "字节模式"
      }
    };
    const submitForm = async () => {
      if (qrInfo.value !== "") {
        try {
          // 使用qrcode库生成二维码，将其转换为Data URL格式
          const dataUrl = await QRCode.toDataURL(qrInfo.value, {
            errorCorrectionLevel: selectedLevel.value,
          });
          qrCodeUrl2.value = dataUrl;
        } catch (error) {
          console.error('生成二维码时出错：', error);
        }
      }

    };
    const submitForm2 = async () => {
      if (qrInfo.value !== "") {
        if (checkInputValidity()) {
          try {
            // 使用qrcode库生成二维码，传入相应参数并转换为Data URL格式
            const dataUrl = await QRCode.toDataURL(qrInfo.value, {
              errorCorrectionLevel: selectedLevel.value,
              encodeURI: selectedEncoding.value
            });

            qrCodeUrl1.value = dataUrl

          } catch (error) {
            alert(error)
            //console.error('生成二维码时出错：', error);
          }
        }

      }
    };
    const checkInputValidity = () => {
      const isNumeric = /^\d+$/.test(qrInfo.value);
      if (!isNumeric) {
        // 根据编码方式检查内容是否符合要求
        if (selectedEncoding.value === 'numeric') {
          alert('数字编码模式下，只能输入数字。')
          return false
        }

      } else {
        if (selectedEncoding.value === 'byte') {
          alert('请选择数字编码模式。')
          return false
        }
      }
      return true
    };


    const changeTab = (type) => {
      tabType.value = type
      if (type === "1") {
        button1Class.value = "selTab"
        button2Class.value = "defaultTab"
      } else {
        button1Class.value = "defaultTab"
        button2Class.value = "selTab"
      }
    }


    return {
      selectedLevel,
      selectedVersion,
      selectedEncoding,
      selectedLevelinfo,
      selectedVersioninfo,
      selectedEncodinginfo,
      submitForm,
      submitForm2,
      changeTab,
      qrInfo,
      numbers,
      tabType,
      button1Class,
      button2Class,
      qrCodeUrl,
      qrCodeUrl1,
      qrCodeUrl2,
      myImg,
      myImg1,
      onImageLoad2,
      onImageLoad1,
      getEncodeing,
      saveImage,
      myImg2
    }
  },

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.minput {
  height: 30px;
  border: 1px solid #ffffff;
  background: #F2F3F5;
  border-radius: 2px;
  box-sizing: border-box;
  padding: 0 5px;
}

.defaultTab {
  width: 70px;
  height: 24px;
  font-size: 12px;
  border-radius: 12px;
  color: #4E5969;
  background: white;
}

.selTab {
  width: 70px;
  height: 24px;
  background: #F2F3F8;
  font-size: 12px;
  border-radius: 12px;
  color: #1664FF;
}

.container_set {
  padding: 5px 20px;
  text-align: left;
}

.save {
  align-items: center;
  display: flex;
  justify-content: center;
  flex-direction: column;
  width: 70%;
  height: 20%;
}

.qrimg {
  width: 152px;
  height: 152px;
  border: 1px solid gray;
  margin-bottom: 5%;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.title {
  margin-bottom: 10px;
  text-align: left;
}

.qrleft {
  flex: 1 1 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.qright {
  flex: 1 1 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.lcontainer {
  display: flex;
  padding: 10px;
  height: 80%;

}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 728px;
}

.card2 {
  width: 70%;
  height: 50%;
  margin-bottom: 10px;
  background: green;
  box-shadow: 0 8px 12px rgba(49, 49, 49, 0.3);
  border-radius: 4px;
  padding: 20px;
  background-color: white;
  transition: box-shadow 0.3s ease;
}

.card1 {
  width: 70%;
  height: 35%;
  margin-bottom: 20px;
  margin-top: 10px;
  background: green;
  box-shadow: 0 8px 12px rgba(49, 49, 49, 0.3);
  border-radius: 4px;
  padding: 20px;
  background-color: white;
  transition: box-shadow 0.3s ease;
}

.card:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
  /* 鼠标悬停时加深阴影效果，营造悬浮起来的感觉 */
}

.card:last-child {
  margin-bottom: 0;

  /* 移除最后一个卡片的底部间距，使其符合要求 */
}
</style>
